package web.services.impl;

import web.search.IndexHolder;
import web.search.SearchHelper;
import web.search.Searchable;
import web.services.HomeService;
import web.services.LocationService;
import web.services.LuceneSearchService;
import web.services.PropertyAnalyst;
import web.util.DateUtil;
import web.util.StringOperateUtil;
import com.feelafter.index.bean.NewsXm;
import com.feelafter.index.bean.SuccessNewsXm;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Sort;
import org.apache.lucene.search.SortField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tool.GetLocationFromTitle;
import web.services.LuceneSearchService;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by Administrator on 2016/3/15.
 */
@Service
public class LuceneSearchServiceImpl implements LuceneSearchService {


    @Autowired
    private PropertyAnalyst propertyAnalysts;
    @Autowired
    private LocationService locationService;
    @Autowired
    private HomeService homeService;

    private final static Logger LOGGER= Logger.getLogger(LuceneSearchServiceImpl.class);

    static IndexHolder holder_0;
    static IndexHolder holder_1;

    public final static int TYPE_SEARCH=0;
    public final static int TYPE_UNSEARCH=1;


    private String index=null;
    private String index_1=null;


    //临时建立索引路径
    private static String indexFolder = "D:/tender/temp";

    private synchronized void getHolder(){
        if(index==null){
            index=propertyAnalysts.getIndexUrl();
        }
        if(index_1==null){
            index_1=propertyAnalysts.getIndexUrl_1();
        }
        if (holder_0==null){
            try {
                holder_0 = IndexHolder.init(index);
            } catch (Exception e) {
                LOGGER.error("索引位置不对,切换索引位置:"+index);
            }
        }
        if (holder_1==null){
            try {
                holder_1 = IndexHolder.init(index_1);
            } catch (IOException e) {
                e.printStackTrace();
                LOGGER.error("索引位置不对,切换索引位置:"+index_1);
            }
        }
    }

    @Override
    public List<Map<String,Object>> searchSimple(int num, String all_search_key, String search_key, String un_search_key,String provinceId,
                                        String city,Integer itemAmount, String qualification,int status, int type) {


        final List<String> listKey= Arrays.asList((all_search_key.trim()+" "+search_key.trim()).split(" "));
        List<Map<String,Object>> list=new ArrayList<Map<String, Object>>();
        if(type==TYPE_SEARCH &&!search_key.equals("")){
                un_search_key="";
        }

            list = search(num, StringOperateUtil.updateRelation(all_search_key, "OR"), StringOperateUtil.updateRelation(search_key, "OR")
                    , StringOperateUtil.updateRelation(un_search_key, "OR"), StringOperateUtil.updateRelation(provinceId+" "+city, "OR"),  itemAmount.toString(), StringOperateUtil.updateRelation(qualification, "OR"), CONTENT_TYPE, type);


        for(Map<String,Object> map:list){

            if(type==TYPE_SEARCH){
                map.put("type",status);
            }else{
                map.put("type",status+""+status);
            }
//            searchNewsScore(listKey,map);
        }
        return list;
    }
    public void searchNewsScore( List<String> listKey,Map<String,Object> map){

        int update=0;
        for (int i = 0; i < listKey.size(); i++) {
            if (Integer.parseInt(map.get("etime").toString()) == 0) {

                if (i == listKey.size() - 1 && !map.get("title").toString().contains(listKey.get(i))) {
                    update=5;
                }

            } else {


                if (i == listKey.size() - 1 && !map.get("title").toString().contains(listKey.get(i))) {
                    update=2;
                }

            }

        }
        for (int i = 0; i < listKey.size(); i++) {
            if (Integer.parseInt(map.get("etime")+"") == 0) {
                if (map.get("title").toString().contains(listKey.get(i))) {
                    update=4;
                    break;
                }

            }else{
                if (map.get("title").toString().contains(listKey.get(i))) {
                    update=1;
                    break;
                }
            }
        }
        if(Integer.parseInt(map.get("type").toString())<10){
            map.put("score",update);
        }else{
            map.put("score",update*10);
        }
    }


    /**
     * 通过关键词搜索
     * @param key
     * @return
     */
    @Override
    public List<Map<String,Object>> search(String key){
        return search(500,key,"","","","0","",CONTENT_TYPE,0);
    }


    @Override
    public Map<String, Object> search(String key,String location,int type,String qualification, int num,int nowPage) {
        String allSearchKey="";
        String searchKey="";
        String unSearchkey="";
        String []keysUpate =key.split(" ");
        String []keys=StringOperateUtil.updateList(keysUpate).split(" ");

        for (String s : keys) {
            if(s.startsWith("+")){
                searchKey+=" "+s;
            }else if(s.startsWith("-")){
                unSearchkey+=" "+s;
            }else{
                allSearchKey+=" "+s;
            }
        }

        Map<String,Object> map=new HashMap<String, Object>();
        if(type==0) {
            map=search(
                    num,
                    StringOperateUtil.updateRelation_DY(allSearchKey.trim(), "OR"),
                    StringOperateUtil.updateRelation_DY(searchKey.trim(), "AND"),
                    StringOperateUtil.updateRelation_DY(unSearchkey.trim(), "OR"),
                    location,"0",StringOperateUtil.updateRelation_DY(qualification, "OR"),CONTENT_TYPE,0,nowPage);
        }else{
            map = searchSuccess(num,
                    StringOperateUtil.updateRelation_DY(allSearchKey.trim(), "OR"),
                    StringOperateUtil.updateRelation_DY(searchKey.trim(), "AND"),
                    StringOperateUtil.updateRelation_DY(unSearchkey.trim(), "OR"),location,CONTENT_TYPE,nowPage);
        }

        return map;
    }

    /**
     *通过关键词与省份搜索
     * @param key
     * @param location
     * @param type 0:招标 1：中标
     * @return
     */

    @Override
    public List<Map<String,Object>> search(String key,String location,int type,String qualification){
        if(type==0) {
            return search(500, StringOperateUtil.updateRelation_DY(key, "OR"), "", "", location, "0", StringOperateUtil.updateRelation(qualification, "OR"), CONTENT_TYPE, 0);
        }else{
            return searchSuccess(500,StringOperateUtil.updateRelation(key,"OR"),"","",location,CONTENT_TYPE);
        }
    }

    /**
     * 不实时搜索，含有更多列数据
     * @param key
     * @param province
     * @param time
     * @return
     */
    public List<Map<String,Object>> search(String key,String province,String time,int num){
        if(key.equals("")){
            return new ArrayList<Map<String, Object>>();
        }
        List<Map<String,Object>> list= searchAdmin(num, StringOperateUtil.updateRelation_DY(key, "AND"), "", "", province, "0", "", CONTENT_TYPE, 0, time);
        for (Map<String, Object> map : list) {
            Map<String,Object> mapNews=homeService.findTenderMap(map.get("district_news_id")+"",map.get("province_id").toString());
            //map.put("subscriber", mapNews.get("subscriber"));
            map.put("subscriber", StringOperateUtil.reStrings(mapNews.get("subscriber") + ""));//处理掉特殊字符
            map.put("subscriber_contact",mapNews.get("subscriber_contact"));
            map.put("subscriber_phone", mapNews.get("subscriber_phone"));
        }
        return list;
    }



    public List<Map<String,Object>> search(int num,String all_search_key,String search_key,String un_search_key
            ,String provinceId,String itemAmount,String qualification,int searchType,int type){
        return searchAdmin(num, all_search_key, search_key, un_search_key, provinceId, itemAmount, qualification, searchType, type,"0");
    }



    /**
     * 中标luce搜索
     * @param num
     * @param key
     * @param provinceId
     * @param searchType
     * @return
     */
    public List<Map<String,Object>> searchSuccess(int num ,String key,String search_key,String un_search_key,String provinceId,int searchType){
        if(StringUtils.isBlank(key)){
            new ArrayList<SuccessNewsXm>();
        }
        getHolder();
        String searchField ;
        if (searchType==TITLE_TYPE){
            searchField=TITLE_STR;
        }else{
            searchField=CONTENT_STR;
        }
        Query query=null;

//        创建搜索条件
        List<String> queriList=new ArrayList<String>();
        List<String> fieldList=new ArrayList<String>();
        List<BooleanClause.Occur> flagList=new ArrayList<BooleanClause.Occur>();


        //添加搜索数据-专属关键词
        if(!StringUtils.isBlank(search_key)){
            queriList.add(search_key);
            fieldList.add(searchField);
            flagList.add(BooleanClause.Occur.MUST);
        }
        //添加搜索数据-不包含关键词
        if(!StringUtils.isBlank(un_search_key)){
            queriList.add(un_search_key);
            fieldList.add(searchField);
            flagList.add(BooleanClause.Occur.MUST_NOT);
        }


//        提那家搜索数据-包含关键词
        queriList.add(key);
        fieldList.add(searchField);
        flagList.add(BooleanClause.Occur.MUST);

        if(!provinceId.equals("") && !provinceId.equals("0")){
            queriList.add(provinceId);
            fieldList.add("district");
            flagList.add(BooleanClause.Occur.MUST);
        }
        query = SearchHelper.makeQuery(fieldList.toArray(new String[fieldList.size()]), queriList.toArray(new String[queriList.size()])
                ,flagList.toArray(new BooleanClause.Occur[flagList.size()]),1.0f);
        List<Class<? extends Searchable>> list = new ArrayList<Class<? extends Searchable>>();
        list.add(SuccessNewsXm.class);
        List<Searchable> newsList=null;


        try {
            newsList = holder_1.find(list,query,null,
                    new Sort(new SortField[]{new SortField("successful_time", SortField.Type.INT,true)}),1,num);
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<Map<String,Object>> listNews=new ArrayList<Map<String, Object>>();
        for (Searchable searchable : newsList) {
            SuccessNewsXm successNewsXm=(SuccessNewsXm)searchable;
            Map<String,Object> map=new HashMap<String, Object>();
            map.put("title",successNewsXm.getTitle());
            map.put("district_news_id", successNewsXm.getDistrictNewsId());
            map.put("successful_time", successNewsXm.getSuccessful_time());
            map.put("provinceId",successNewsXm.getProvince());
            map.put("cityId",successNewsXm.getCity());
            map.put("win_bid_figure",successNewsXm.getWin_bid_figure());
            /* 提取摘要时，用到正文 */
            /*map.put("content",successNewsXm.getContent());*/

            /*map.put("stime",DateUtil.getStringDate(Integer.parseInt(successNewsXm.getStime()),"yyyy-MM-dd"));
            map.put("starTime",DateUtil.getStringDate(Integer.parseInt(successNewsXm.getStime()),"yyyy-MM-dd"));*/
            map.put("stime",DateUtil.getStringDate(Integer.parseInt(successNewsXm.getSuccessful_time()), "yyyy-MM-dd"));
            map.put("starTime",DateUtil.getStringDate(Integer.parseInt(successNewsXm.getSuccessful_time()), "yyyy-MM-dd"));
            if(Integer.parseInt(successNewsXm.getSuccessful_time())==0){
                map.put("stime","");
                map.put("stime","");
            }
            String district="";
            if(Integer.parseInt(map.get("provinceId").toString())>100000){
                district+=locationService.getLocationMap().get(map.get("provinceId").toString());
                if(Integer.parseInt(map.get("cityId").toString())>0){
                    String city=locationService.getLocationMap().get(map.get("cityId").toString())+"";
                    if(!city.equals("null") && !city.equals("")) {
                        district += "  " +city;
                    }
                }

            /* 返回数据前对没有地域的地区进行地域处理 */
            }else{
                int t_code=GetLocationFromTitle.getLocation(map.get("title").toString());
                if(t_code!=0 ){
                    if(t_code%10000==0){
                        map.put("provinceId",t_code);
                        district+=locationService.getLocationMap().get(map.get("provinceId").toString());
                    }else{
                        map.put("cityId",t_code);
                        map.put("provinceId", t_code/10000*10000);
                        district+=locationService.getLocationMap().get(map.get("provinceId").toString());
                        district+=" "+locationService.getLocationMap().get(map.get("cityId").toString());
                    }
                }
            }
            map.put("district",district);

            listNews.add(map);
        }

        return listNews;
    }

    /**
     * 重写中标搜索
     * @param num
     * @param key
     * @param search_key
     * @param un_search_key
     * @param provinceId
     * @param searchType
     * @param nowPage
     * @return
     */
    public Map<String,Object> searchSuccess(int num ,String key,String search_key,String un_search_key,String provinceId,int searchType,int nowPage){
        String logStr="\n";
        long logTime=System.currentTimeMillis();

        Map<String,Object> rsMap=new HashMap<String, Object>();

        getHolder();
        String searchField ;
        if (searchType==TITLE_TYPE){
            searchField=TITLE_STR;
        }else{
            searchField=CONTENT_STR_INDEX;
        }
        Query query=null;
//        创建搜索条件
        List<String> queriList=new ArrayList<String>();
        List<String> fieldList=new ArrayList<String>();
        List<BooleanClause.Occur> flagList=new ArrayList<BooleanClause.Occur>();

        //stime>0
        queriList.add("["+0+" TO "+DateUtil.getNowToInt()+"]");
        fieldList.add("stime");
        flagList.add(BooleanClause.Occur.MUST);

        //添加搜索数据-专属关键词
        if(!StringUtils.isBlank(search_key)){
            queriList.add(search_key);
            fieldList.add(searchField);
            flagList.add(BooleanClause.Occur.MUST);
        }
        //添加搜索数据-不包含关键词
        if(!StringUtils.isBlank(un_search_key)){
            queriList.add(un_search_key);
            fieldList.add(searchField);
            flagList.add(BooleanClause.Occur.MUST_NOT);
        }
//        提那家搜索数据-包含关键词
        if(!StringUtils.isBlank(key)) {
            queriList.add(key);
            fieldList.add(searchField);
            flagList.add(BooleanClause.Occur.MUST);
        }
        if(!provinceId.equals("") && !provinceId.equals("0")){
            queriList.add(provinceId);
            fieldList.add("district");
            flagList.add(BooleanClause.Occur.MUST);
        }
        query = SearchHelper.makeQuery(fieldList.toArray(new String[fieldList.size()]), queriList.toArray(new String[queriList.size()])
                ,flagList.toArray(new BooleanClause.Occur[flagList.size()]),1.0f);
        List<Class<? extends Searchable>> list = new ArrayList<Class<? extends Searchable>>();
        list.add(SuccessNewsXm.class);
        List<Searchable> newsList=null;

        logStr+="条件处理："+(System.currentTimeMillis() - logTime)+"; \n";
        logTime=System.currentTimeMillis();

        int count=0;
        try {
//            newsList = holder_1.findUpdate(SuccessNewsXm.class, query, null,
//                    new Sort(new SortField[]{new SortField("stime", SortField.Type.INT, true)}), nowPage, num);
            newsList = holder_1.find(list,query,null,new Sort(new SortField[]{new SortField("stime", SortField.Type.INT, true)}),nowPage, num);
            rsMap.put("findTime",(System.currentTimeMillis() - logTime));

            logStr+="find耗时："+(System.currentTimeMillis() - logTime)+",长度："+newsList.size()+"; \n";
            logTime=System.currentTimeMillis();

//            if(nowPage==1) count=holder_1.countUpdate(SuccessNewsXm.class , query, null);
            if(nowPage==1) count=holder_1.count(list,query, null);
            rsMap.put("countTime",(System.currentTimeMillis() - logTime));

            logStr+="count耗时："+(System.currentTimeMillis() - logTime)+",count:"+count+"; \n";
            logTime=System.currentTimeMillis();

        } catch (IOException e) {
            e.printStackTrace();
        }

        List<Map<String,Object>> listNews=new ArrayList<Map<String, Object>>();
        for (Searchable searchable : newsList) {
            SuccessNewsXm successNewsXm=(SuccessNewsXm)searchable;
            Map<String,Object> map=new HashMap<String, Object>();
            map.put("title",successNewsXm.getTitle());
            map.put("district_news_id", successNewsXm.getDistrictNewsId());
            map.put("successful_time", successNewsXm.getSuccessful_time());
            map.put("provinceId",successNewsXm.getProvince());
            map.put("cityId",successNewsXm.getCity());
            map.put("win_bid_figure",successNewsXm.getWin_bid_figure());
            /* 提取摘要时，用到正文 */
            map.put("content",successNewsXm.getContent());

            map.put("stime",Integer.parseInt(successNewsXm.getStime())<0?"0":successNewsXm.getStime());
            map.put("starTime",DateUtil.getStringDate(Integer.parseInt(map.get("stime")+""),"yyyy-MM-dd"));
            /*map.put("stime",DateUtil.getStringDate(Integer.parseInt(successNewsXm.getSuccessful_time()),"yyyy-MM-dd"));
            map.put("starTime",DateUtil.getStringDate(Integer.parseInt(successNewsXm.getSuccessful_time()),"yyyy-MM-dd"));*/
//            if(Integer.parseInt(successNewsXm.getSuccessful_time())==0){
//                map.put("stime","0");
//                map.put("starTime","");
//            }

            String district="";
            if(Integer.parseInt(map.get("provinceId").toString())>100000){
                district+=locationService.getLocationMap().get(map.get("provinceId").toString());
                if(Integer.parseInt(map.get("cityId").toString())>0){
                    String city=locationService.getLocationMap().get(map.get("cityId").toString())+"";
                    if(!city.equals("null") && !city.equals("")) {
                        district += "  " +city;
                    }
                }
            /* 返回数据前对没有地域的地区进行地域处理 */
            }else{
                int t_code=GetLocationFromTitle.getLocation(map.get("title").toString());
                if(t_code!=0 ){
                    if(t_code%10000==0){
                        map.put("provinceId",t_code);
                        district+=locationService.getLocationMap().get(map.get("provinceId").toString());
                    }else{
                        map.put("cityId",t_code);
                        map.put("provinceId", t_code/10000*10000);
                        district+=locationService.getLocationMap().get(map.get("provinceId").toString());
                        district+=" "+locationService.getLocationMap().get(map.get("cityId").toString());
                    }
                }
            }
            map.put("district",district);

            listNews.add(map);
        }

        logStr+="lucene数据处理耗时："+(System.currentTimeMillis() - logTime)+"; \n";
        LOGGER.info(logStr+"--------------------------------------------");

        rsMap.put("list",listNews);
        rsMap.put("count",count);
        return rsMap;
    }


    /**
     * lucene招标搜索
     * @param num
     * @param all_search_key
     * @param search_key
     * @param un_search_key
     * @param provinceId
     * @param itemAmount
     * @param qualification
     * @param searchType
     * @param type
     * @return
     */
    public List<Map<String,Object>> searchAdmin(int num,String all_search_key,String search_key,String un_search_key
            ,String provinceId,String itemAmount,String qualification,int searchType,int type,String time){

        if (StringUtils.isBlank(all_search_key) && StringUtils.isBlank(search_key)){
            return new ArrayList<Map<String, Object>>();
        }
        getHolder();
        String searchField ;
        if (searchType==TITLE_TYPE){
            searchField=TITLE_STR;
        }else{
            searchField=CONTENT_STR_INDEX;
        }
        Query query = null;

        //创建搜索条件
        List<String> queriList=new ArrayList<String>();
        List<String> fieldList=new ArrayList<String>();
        List<BooleanClause.Occur> flagList=new ArrayList<BooleanClause.Occur>();

        //添加搜索数据-包含关键词
        if(!StringUtils.isBlank(all_search_key)) {
            queriList.add(all_search_key);
            fieldList.add(searchField);
            flagList.add(BooleanClause.Occur.MUST);
        }
        //添加搜索数据-专属关键词
        if(!StringUtils.isBlank(search_key)){
            queriList.add(search_key);
            fieldList.add(searchField);
            if(type==TYPE_SEARCH){
                flagList.add(BooleanClause.Occur.MUST);
            }else{
                flagList.add(BooleanClause.Occur.MUST_NOT);
            }
        }
        //添加搜索数据-不包含关键词
        if(!StringUtils.isBlank(un_search_key)){
            queriList.add(un_search_key);
            fieldList.add(searchField);
            flagList.add(BooleanClause.Occur.MUST_NOT);
        }
        //搜索资质
        if(!StringUtils.isBlank(qualification)){
            queriList.add(qualification);
            fieldList.add(CONTENT_STR_INDEX);
            flagList.add(BooleanClause.Occur.MUST);
        }

        if(!provinceId.equals("") && !provinceId.equals("0")){
            queriList.add(provinceId);
            fieldList.add("district");
            flagList.add(BooleanClause.Occur.MUST);
        }
        //添加搜索数据-金额
        if(!itemAmount.equals("0")){
            queriList.add(itemAmount);
            fieldList.add("itemAmount");
            flagList.add(BooleanClause.Occur.MUST);
        }
//        时间范围
        if(!time.equals("0")){
            queriList.add("["+time+" TO "+DateUtil.getNowToInt()+"]");
            fieldList.add("stime");
            flagList.add(BooleanClause.Occur.MUST);
        }

//        queriList.add("["+0+" TO "+DateUtil.getNowToInt()+"]");
//        fieldList.add("etime_info");
//        flagList.add(BooleanClause.Occur.MUST_NOT);

        query = SearchHelper.makeQuery(fieldList.toArray(new String[fieldList.size()]), queriList.toArray(new String[queriList.size()])
                ,flagList.toArray(new BooleanClause.Occur[flagList.size()]),1.0f);

        List<Class<? extends Searchable>> list = new ArrayList<Class<? extends Searchable>>();
        list.add(NewsXm.class);
        List<Searchable> newsList=null;

        try {
            newsList = holder_0.find(list,query,null,
                    new Sort(new SortField[]{new SortField("stime", SortField.Type.INT,true)}),1,num);
        } catch (IOException e) {
            e.printStackTrace();
        }


        List<Map<String,Object>> lists=new ArrayList<Map<String, Object>>();
//        Set<String> set=new HashSet<String>();
        for(Searchable searchable:newsList){
            NewsXm newsXm=(NewsXm)searchable;
//            Map<String,Object> map=newsService.getNewsMap(newsXm.getDistrictNewsId(),newsXm.getProvince());

            Map<String,Object>map=new HashMap<String, Object>();
            map.put("district_news_id",newsXm.getDistrictNewsId());
            map.put("qualification",newsXm.getQualification());
            map.put("title",newsXm.getTitle());
            map.put("endTime",DateUtil.getStringDate(Integer.parseInt(newsXm.getEtime()),"yyyy-MM-dd"));
            if(Integer.parseInt(newsXm.getEtime())==0){
                map.put("endTime","");
            }
            map.put("etime",newsXm.getEtime().equals("0")?"2100000000":newsXm.getEtime());
            map.put("etime_info",newsXm.getEtimeInfo().equals("")?"0":newsXm.getEtimeInfo());
            map.put("item_amount",newsXm.getItem_amount());
            map.put("city_id",newsXm.getCity());
            map.put("province_id",newsXm.getProvince());
            map.put("stime",newsXm.getStime());
            if(newsXm.getStime().equals("0")){
                map.put("starTime","");
            }else{
                map.put("starTime",DateUtil.getStringDate(Integer.parseInt(newsXm.getStime())));
            }
            map.put("content",newsXm.getContent());

            String district="";
            if(Integer.parseInt(map.get("province_id").toString())>100000){
                district+=locationService.getLocationMap().get(map.get("province_id").toString());
                if(Integer.parseInt(map.get("city_id").toString())>0){
                    String city=locationService.getLocationMap().get(map.get("city_id").toString())+"";
                    if(!city.equals("null") && !city.equals("")) {
                        district += "  " +city;
                    }
                }
           /* 返回数据前对没有地域的地区进行地域处理 */
            }else{
                int t_code=GetLocationFromTitle.getLocation(map.get("title").toString());
                if(t_code!=0 ){
                    if(t_code%10000==0){
                        map.put("province_id",t_code);
                        district+=locationService.getLocationMap().get(map.get("province_id").toString());
                    }else{
                        map.put("city_id",t_code);
                        //locationService.findProvinceByCity(t_code)
                        map.put("province_id", t_code/10000*10000);
                        district+=locationService.getLocationMap().get(map.get("province_id").toString());
                        district+=" "+locationService.getLocationMap().get(map.get("city_id").toString());
                    }
                }
            }
            map.put("district",district);

            lists.add(map);
        }

        return lists;
    }

    /**
     * 重写lucene搜索方法，加入当前页
     * @param num
     * @param all_search_key
     * @param search_key
     * @param un_search_key
     * @param provinceId
     * @param itemAmount
     * @param qualification
     * @param searchType
     * @param type
     * @param nowPage
     * @return
     */
    public Map<String,Object> search(int num,String all_search_key,String search_key,String un_search_key
            ,String provinceId,String itemAmount,String qualification,int searchType,int type,int nowPage){
        String logStr=" \n";
        long logTime=System.currentTimeMillis();

        Map<String ,Object> rsMap=new HashMap<String, Object>();

        getHolder();
        String searchField ;
        if (searchType==TITLE_TYPE){
            searchField=TITLE_STR;
        }else{
            searchField=CONTENT_STR_INDEX;
        }
        Query query = null;

        //创建搜索条件
        List<String> queriList=new ArrayList<String>();
        List<String> fieldList=new ArrayList<String>();
        List<BooleanClause.Occur> flagList=new ArrayList<BooleanClause.Occur>();

        //过滤过期数据
        queriList.add("["+0+" TO "+DateUtil.getNowToInt()+"]");
        fieldList.add("etime_info");
        flagList.add(BooleanClause.Occur.MUST_NOT);
        //stime>0
        queriList.add("["+0+" TO "+DateUtil.getNowToInt()+"]");
        fieldList.add("stime");
        flagList.add(BooleanClause.Occur.MUST);

        //添加搜索数据-包含关键词
        if(!StringUtils.isBlank(all_search_key)){
            queriList.add(all_search_key);
            fieldList.add(searchField);
            flagList.add(BooleanClause.Occur.MUST);
        }
        //添加搜索数据-专属关键词
        if(!StringUtils.isBlank(search_key)){
            queriList.add(search_key);
            fieldList.add(searchField);
            if(type==TYPE_SEARCH){
                flagList.add(BooleanClause.Occur.MUST);
            }else{
                flagList.add(BooleanClause.Occur.MUST_NOT);
            }
        }
        //添加搜索数据-不包含关键词
        if(!StringUtils.isBlank(un_search_key)){
            queriList.add(un_search_key);
            fieldList.add(searchField);
            flagList.add(BooleanClause.Occur.MUST_NOT);
        }
        //搜索资质
        if(!StringUtils.isBlank(qualification)){
            queriList.add(qualification);
            fieldList.add(CONTENT_STR_INDEX);
            flagList.add(BooleanClause.Occur.MUST);
        }

        if(!provinceId.equals("") && !provinceId.equals("0")){
            if(provinceId.contains("-")){
                provinceId=provinceId.replace("-","");
                queriList.add(provinceId);
                fieldList.add("district");
                flagList.add(BooleanClause.Occur.MUST_NOT);
            }else{
                queriList.add(provinceId);
                fieldList.add("district");
                flagList.add(BooleanClause.Occur.MUST);
            }
        }
        //添加搜索数据-金额
        if(!itemAmount.equals("0")){
            queriList.add(itemAmount);
            fieldList.add("itemAmount");
            flagList.add(BooleanClause.Occur.MUST);
        }

        query = SearchHelper.makeQuery(fieldList.toArray(new String[fieldList.size()]), queriList.toArray(new String[queriList.size()])
                ,flagList.toArray(new BooleanClause.Occur[flagList.size()]),1.0f);

        List<Class<? extends Searchable>> list = new ArrayList<Class<? extends Searchable>>();
        list.add(NewsXm.class);
        List<Searchable> newsList=null;
        int count=0;


        logStr+="条件处理："+(System.currentTimeMillis() - logTime)+"; \n";
        logTime=System.currentTimeMillis();

        try {
            newsList = holder_0.find(list,query,null,
                    new Sort(new SortField[]{new SortField("stime", SortField.Type.INT,true)}),nowPage,num);
            rsMap.put("findTime",(System.currentTimeMillis() - logTime));

            logStr+="find耗时："+(System.currentTimeMillis() - logTime)+",长度："+newsList.size()+"; \n";
            logTime=System.currentTimeMillis();

            if(nowPage==1) count=holder_0.count(list,query,null);
            rsMap.put("countTime",(System.currentTimeMillis() - logTime));

            logStr+="count耗时："+(System.currentTimeMillis() - logTime)+",count:"+count+"; \n";
            logTime=System.currentTimeMillis();

        } catch (IOException e) {
            e.printStackTrace();
        }

        List<Map<String,Object>> lists=new ArrayList<Map<String, Object>>();
//        Set<String> set=new HashSet<String>();
        for(Searchable searchable:newsList){
            NewsXm newsXm=(NewsXm)searchable;
//            Map<String,Object> map=newsService.getNewsMap(newsXm.getDistrictNewsId(),newsXm.getProvince());
            Map<String,Object>map=new HashMap<String, Object>();
            map.put("district_news_id",newsXm.getDistrictNewsId());
            map.put("qualification",newsXm.getQualification());
            map.put("title",newsXm.getTitle());
            map.put("endTime",DateUtil.getStringDate(Integer.parseInt(newsXm.getEtime()),"yyyy-MM-dd"));
            if(Integer.parseInt(newsXm.getEtime())==0){
                map.put("endTime","");
            }
            map.put("etime",newsXm.getEtime().equals("0")?"2100000000":newsXm.getEtime());
            map.put("etime_info",newsXm.getEtimeInfo().equals("")?"0":newsXm.getEtimeInfo());
            map.put("item_amount",newsXm.getItem_amount());
            map.put("city_id",newsXm.getCity());
            map.put("province_id",newsXm.getProvince());
            map.put("stime",newsXm.getStime());
            if(Integer.parseInt(newsXm.getStime())<=0){
                map.put("starTime","");
            }else{
                map.put("starTime",DateUtil.getStringDate(Integer.parseInt(newsXm.getStime())));
            }

            /* 提取摘要时，用到正文 */
            map.put("content",newsXm.getContent());

            String district="";
            if(Integer.parseInt(map.get("province_id").toString())>100000){
                district+=locationService.getLocationMap().get(map.get("province_id").toString());
                if(Integer.parseInt(map.get("city_id").toString())>0){
                    String city=locationService.getLocationMap().get(map.get("city_id").toString())+"";
                    if(!city.equals("null") && !city.equals("")) {
                        district += "  " +city;
                    }
                }
           /* 返回数据前对没有地域的地区进行地域处理 */
            }else{
                int t_code=GetLocationFromTitle.getLocation(map.get("title").toString());
                if(t_code!=0 ){
                    if(t_code%10000==0){
                        map.put("province_id",t_code);
                        district+=locationService.getLocationMap().get(map.get("province_id").toString());
                    }else{
                        map.put("city_id",t_code);
                        //locationService.findProvinceByCity(t_code)
                        map.put("province_id", t_code/10000*10000);
                        district+=locationService.getLocationMap().get(map.get("province_id").toString());
                        district+=" "+locationService.getLocationMap().get(map.get("city_id").toString());
                    }
                }
            }
            map.put("district",district);

//            lists.add(map);
            if(map.get("title")!=null) {
                lists.add(map);
            }
        }

        logStr+="lucene数据处理耗时："+(System.currentTimeMillis() - logTime) + "; \n";
        LOGGER.info(logStr + "--------------------------------------------");
        rsMap.put("list",lists);
        rsMap.put("count", count);
        return rsMap;
    }





    public static IndexHolder setUp() throws Exception {

        try {
            FileUtils.deleteDirectory(new File(indexFolder));

            FileUtils.forceMkdir(new File(indexFolder));
        }catch (IOException e){

        }
        return IndexHolder.init(indexFolder);
    }

    /**
     * 通过公式计算获取数据得分
     * @return
     */
    @Override
    public Map<Long, Double> getScoreCompute(List<Map<String,Object>> listNews,String name){
        Map<Long,Double> map=new HashMap<Long, Double>();
        for (Map<String, Object> listNew : listNews) {
            int num=0;
            String titleKey=listNew.get("title_key").toString();
            String[] names=name.split(" ");
            int nameNum=names.length;
            String [] titleKeys=titleKey.split(" ");
            int titleKeyNum=titleKeys.length;
            for (String s : names) {
                for (String key : titleKeys) {
                    if(s.equals(key)) {
                        num++;
                        break;
                    }

                }
            }
            double score=1d*num*num/nameNum/titleKeyNum;
            map.put(Long.parseLong(listNew.get("id")+""),score);

        }
        return map;
    }
}
